<template>
  <div class="app-container">
    <el-dialog :title="!form.id ? '新增' : '修改'" :visible.sync="open" width="1300px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="转换单号" prop="materialConversionsCode" >
              <el-input v-model="form.materialConversionsCode" :disabled="form.id ? true : false" placeholder="请输入转换单号" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="4" v-if="!disabled">
            <el-form-item label-width="80">
              <el-switch v-model="autoGenFlag"
                         active-color="#13ce66"
                         active-text="自动生成"
                         @change="handleAutoGenChange(autoGenFlag)">
              </el-switch>
            </el-form-item>
          </el-col>-->
          <el-col :span="12">
            <el-form-item label="单据日期" prop="billDate">
              <el-date-picker clearable style="width: 80%" :disabled="disabled"
                              v-model="form.billDate"
                              type="date"
                              value-format="yyyy-MM-dd"
                              :default-value="new Date()"
                              placeholder="请选择单据日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="出库仓库" prop="outWarehouseId" >
              <!--             <el-input v-model="form.outWarehouseId" placeholder="请输入出库仓库ID" />-->
              <el-select v-model="form.outWarehouseId" placeholder="请选择出库仓库" :disabled="disabled" @change="handleOutWarehouseChange" style="width: 80%">
                <el-option
                    v-for="warehouse in warehouseList"
                    :key="warehouse.warehouseId"
                    :label="warehouse.warehouseName"
                    :value="warehouse.warehouseId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库仓库" prop="intWarehouseId">
              <!--             <el-input v-model="form.intWarehouseId" placeholder="请输入入库仓库ID" />-->
              <el-select v-model="form.intWarehouseId" placeholder="请选择入库仓库"  :disabled="disabled" @change="handleInWarehouseChange" style="width: 80%">
                <el-option
                    v-for="warehouse in warehouseList"
                    :key="warehouse.warehouseId"
                    :label="warehouse.warehouseName"
                    :value="warehouse.warehouseId">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

        </el-row>
      </el-form>

      <el-card style="border-radius: 10px">
        <el-tabs v-model="activeName" @tab-click="handleClick" style="height: 100%">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['wm:line:add']"
          >新增</el-button>
        </el-col>

<!--          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              size="mini"
              v-if="activeName == 'second'"
              @click="handleAdd"
              v-hasPermi="['wm:line:add']"
            >费用分摊</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-edit"
              size="mini"
              v-if="activeName == 'second'"
              @click="handleAdd"
              v-hasPermi="['wm:line:add']"
            >差异金额分摊</el-button>
          </el-col>-->

        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

<!--   新建和单据头同时进行保存的  涉及在不同字段表里直接操作   转换前 转换后 就写了两个tabel      -->
          <!--   现在要辅助单位相关加字段  要加两次，  哈哈哈哈哈  -->
      <el-tab-pane label="转换前" name="first">
<!--        <el-form ref="beforeForm" :model="beforeForm" :rules="rules" label-width="80px">-->
          <el-table v-loading="loading" :data="form.beforeList" @selection-change="handleSelectionChange">
            <el-table-column type="index" label="序号" width="55" align="center" />
            <el-table-column label="产品物料编码" align="center" prop="itemCode" />
            <el-table-column label="产品物料名称" align="center" prop="itemName" />
            <el-table-column label="规格型号" align="center" prop="specification" />
            <el-table-column label="批次号" align="center" prop="batchCode" />
            <el-table-column label="仓库" align="center" prop="warehouseName" />
            <el-table-column label="库区" align="center" prop="locationName" />
            <el-table-column label="库位" align="center" prop="areaName" />

<!--            <el-table-column label="仓库ID" align="center" prop="warehouseId" />
            <el-table-column label="仓库编码" align="center" prop="warehouseCode" />
            <el-table-column label="仓库名称" align="center" prop="warehouseName" />
            <el-table-column label="库区ID" align="center" prop="locationId" />
            <el-table-column label="库区编码" align="center" prop="locationCode" />
            <el-table-column label="库区名称" align="center" prop="locationName" />
            <el-table-column label="库位ID" align="center" prop="areaId" />
            <el-table-column label="库位编码" align="center" prop="areaCode" />
            <el-table-column label="库位名称" align="center" prop="areaName" />-->
            <el-table-column label="单价" align="center" prop="price" />
            <el-table-column label="换算方式" align="center" prop="storageUnitType" >
              <template slot-scope="scope">
                <span v-if="scope.row.storageUnitType === 'fixed'"  >固定</span>
                <span v-if="scope.row.storageUnitType === 'float'"  >浮动</span>
              </template>
            </el-table-column>
            <el-table-column label="换算比例" align="center" prop="storageRatio" />
            <el-table-column label="单位（主）" align="center" prop="unitOfMeasure" fixed="right"/>
            <!--:precision="2"-->
            <el-table-column label="转换数量（主）" align="center" prop="quantityConversion" width="150" fixed="right">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantityConversion" size="mini" @change="handleEditZhu(scope.$index, scope.row)"
                                 controls-position="right" :min="0" style="width:100%"  ></el-input-number>
              </template>
            </el-table-column>

            <el-table-column label="单位（辅）" align="center" prop="storageUnit" fixed="right"/>
            <el-table-column label="转移数量（辅）" align="center" prop="storageUnitquantity" width="150" fixed="right">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.storageUnitquantity" :disabled="'N' == scope.row.enableMultiUnit" size="mini" @change="handleEditFu(scope.$index, scope.row)"
                                 controls-position="right" style="width:100%" ></el-input-number>
              </template>
            </el-table-column>
<!--            <el-table-column label="库存状态" align="center" prop="stockStatus" />-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.$index, scope.row)"
                    v-hasPermi="['wm:line:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

<!--          <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
          />-->

<!--        </el-form>-->
      </el-tab-pane>
      <el-tab-pane label="转换后" name="second" :key="tableKey">

<!--        <el-form ref="afterForm" :model="afterForm" :rules="rules1" label-width="80px">-->
          <el-table v-loading="loading" :data="form.afterList" @selection-change="handleSelectionChange">
            <el-table-column type="index" label="序号" width="55" align="center" />
            <el-table-column label="物料编码" align="center" prop="itemCode" />
            <el-table-column label="物料名称" align="center" prop="itemName" />
            <el-table-column label="规格型号" align="center" prop="specification" />

            <el-table-column label="批次号" align="center" prop="batchCode" width="300">
              <template slot-scope="scope">
                <div style="display: flex; align-items: center; gap: 8px">
                  <el-input v-model="scope.row.batchCode" :disabled="scope.row.enableBatchFlag !=='Y'"  placeholder="批次号" />
                  <el-switch
                    v-if ="scope.row.enableBatchFlag =='Y'"
                    v-model="scope.row.autoGenCodeFlag"
                    active-color="#13ce66"
                    active-text="自动生成"
                    @change="handleLineAutoGenCode(scope.row.autoGenCodeFlag,scope.row)"
                  >
                  </el-switch>
                </div>
              </template>
            </el-table-column>
<!--            <el-table-column label="仓库ID" align="center" prop="warehouseId" />-->
<!--            <el-table-column label="仓库编码" align="center" prop="warehouseCode" />-->
            <el-table-column label="仓库名称" align="center" prop="warehouseName" width="80" />
            <el-table-column label="库区" align="center" prop="locationId"  width="220">
              <template slot-scope="scope">
                <el-select v-model="scope.row.locationId" placeholder="请选择库区" @change="handleLocationChange($event,scope.row)" >
                  <el-option
                    v-for="item in locationList"
                    :key="item.locationId"
                    :label="item.locationName"
                    :value="item.locationId">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
<!--            <el-table-column label="库区编码" align="center" prop="locationCode" />
            <el-table-column label="库区名称" align="center" prop="locationName" />-->
            <el-table-column label="库位" align="center" prop="areaId" width="220">
              <template slot-scope="scope">
                  <el-select v-model="scope.row.areaId" placeholder="请选择库位"
                             @change="handleAreaChange($event,scope.row)"
                             @visible-change="handleVisibleChange(($event,scope.row))"
                             v-loading="areaSelectLoading">
                    <el-option
                      v-for="item in areaList"
                      :key="item.areaId"
                      :label="item.areaName"
                      :value="item.areaId">
                    </el-option>
                  </el-select>
              </template>

            </el-table-column>
<!--            <el-table-column label="库位编码" align="center" prop="areaCode" />
            <el-table-column label="库位名称" align="center" prop="areaName" />-->

            <el-table-column label="单价" align="center" prop="price" width="150">
              <template slot-scope="scope">
              <el-input-number class="item__input" v-model="scope.row.price" placeholder="请输入价格"
                                    style="width:100%"
                               :min="0"
                               :max="1000000"
                               :precision="2"
                               controls-position="right"
                              ></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="换算方式" align="center" prop="storageUnitType" >
              <template slot-scope="scope">
                <span v-if="scope.row.storageUnitType === 'fixed'"  >固定</span>
                <span v-if="scope.row.storageUnitType === 'float'"  >浮动</span>
              </template>
            </el-table-column>
            <el-table-column label="换算比例" align="center" prop="storageRatio" />
            <el-table-column label="单位（主）" align="center" prop="unitOfMeasure" fixed="right"/>
            <el-table-column label="转换数量（主）" align="center" prop="quantityConversion" width="150" fixed="right">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.quantityConversion" controls-position="right"    @change="handleEditZhu(scope.$index, scope.row)" style="width: 100%"></el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="单位（辅）" align="center" prop="storageUnit" fixed="right"/>
            <el-table-column label="转换数量（辅）" align="center" prop="storageUnitquantity" width="150" fixed="right">
              <template slot-scope="scope">
                <el-input-number v-model="scope.row.storageUnitquantity" :disabled="'N' == scope.row.enableMultiUnit" size="mini" @change="handleEditFu(scope.$index, scope.row)"
                                 controls-position="right" style="width:100%" ></el-input-number>
              </template>
            </el-table-column>
<!--            <el-table-column label="入库时间" align="center" prop="recptDate" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.recptDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>-->
<!--            <el-table-column label="库存状态" align="center" prop="stockStatus" />-->
<!--            <el-table-column label="生产日期" align="center" prop="manufactureDate" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.manufactureDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="库存有效期" align="center" prop="expireDate" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.expireDate, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>-->
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">>
              <template slot-scope="scope">
<!--                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleUpdate(scope.row)"
                    v-hasPermi="['wm:line:edit']"
                >修改</el-button>-->
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.$index, scope.row)"
                    v-hasPermi="['wm:line:remove']"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>

<!--          <pagination
              v-show="total>0"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
          />-->
<!--        </el-form>-->
      </el-tab-pane>

    </el-tabs>
      </el-card>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <StockSelect ref="outSelect"  @onSelected="onStockSelected"></StockSelect>
    <ItemSelect ref="inSelect"  @onSelected="onItemSelected"></ItemSelect>
  </div>
</template>

<script>
import { listLine, getLine, delLine, addLine, updateLine } from "@/api/mes/wm/materialconversionline";
import {
  addMaterialconversions, addMaterialconversionsAll,
  getMaterialconversions,
  updateMaterialconversions, updateMaterialconversionsAll
} from "@/api/mes/wm/materialconversions";
import StockSelect from "@/components/stockSelect/single.vue"
import ItemSelect from "@/components/itemSelect/single.vue"

import {getLocationList} from "@/api/mes/wm/location";
import {getAreaList, getListByWarehouseId} from "@/api/mes/wm/area";
import {genCode} from "@/api/system/autocode/rule";
import {getWarehouseList} from "@/api/mes/wm/warehouse";
import {getMdItem} from "@/api/mes/md/mdItem";
export default {
  name: "Line",
  props: {
    title: null,
  },
  components:{StockSelect,ItemSelect},
  data() {
    return {

      disabled:false,
      autoGenFlag:false,
      optType: undefined,
      warehouseList:[],
      //自动生成批次号
      // autoGenCodeFlag: false,
      activeName: 'first',
      areaSelectLoading:false,
      locationList:[],
      areaList:[],
      tableKey:0,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 形态转换单单据体表格数据
      lineList: [],
      // 弹出层标题

      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        materialConversionId: this.materialConversionId,        materialConversionType: null,        itemId: null,        itemCode: null,        itemName: null,        specification: null,        unitOfMeasure: null,        batchCode: null,        warehouseId: null,        warehouseCode: null,        warehouseName: null,        locationId: null,        locationCode: null,        locationName: null,        areaId: null,        areaCode: null,        areaName: null,      },
      // 表单参数
      form: {
        id:null,
        beforeList:[
        ],
        afterList:[]
      },
   /*   afterForm:{afterList:[],},
      beforeForm:{
        beforeList:[],
      },*/
      // 表单校验
      rules: {
        materialConversionsCode:[
          { required: true, message: "转换单号不能为空", trigger: "blur" }
        ],
        billDate:[
          { required: true, message: "单据日期不能为空", trigger: "blur" }
        ],
        outWarehouseId: [
          { required: true, message: "出库仓库不能为空", trigger: "blur" }
        ],
        intWarehouseId: [
          { required: true, message: "入库仓库不能为空", trigger: "blur" }
        ],
         materialConversionType: [
          { required: true, message: "转换类型不能为空", trigger: "change" }
        ],
        itemId: [
          { required: true, message: "产品物料ID不能为空", trigger: "blur" }
        ]

      },

    };
  },
  created() {
    // this.getList();

  },
  methods: {
    init(materialConversionId){
      this.getWarehouse()
      this.reset()
      if(materialConversionId){
        this.disabled=true
        this.form.id=materialConversionId
      }else{
        this.handleAutoGenChange(true)
        this.form.id=null
        this.disabled=false
      }
      this.open=true

      this.$nextTick(() => {
        if (materialConversionId) {
          getMaterialconversions(materialConversionId).then(response => {
            this.form = response.data;
            this.form.beforeList=response.data.beforeList
            this.form.afterList=response.data.afterList
            //编辑，物料得显示库区库位  这时库位就是入库仓库下的所有库位
            this.getArea()
            // this.getList()
            this.getLocation()
            this.$forceUpdate()
          });
        }
      })

      this.loading=false

    },
    /** 查询形态转换单单据体列表 */
    getList() {
      this.loading = true;
      this.queryParams.materialConversionId=materialConversionId
      if(this.queryParams.materialConversionId){
      this.queryParams.materialConversionType="mcout"
        listLine(this.queryParams).then(response => {
          this.form.beforeList = response.rows;
          this.total = response.total;
          this.loading = false;
        });

      }else{
    /*    this.beforeForm.beforeList=[]
        this.afterForm.afterList=[]*/
        this.loading = false;
      }

    },
    handleEditZhu(index,row) {
      this.$forceUpdate()
      console.log("zhuuuuuuu",row.enableMultiUnit)
      if('Y' == row.enableMultiUnit){
        if (row.storageUnitType === 'fixed') {
          console.log("zhuuuuuuu",row.enableMultiUnit)
          // 辅单位数量=主数量 / 换算比例
          row.storageUnitquantity = parseFloat(
            (row.quantityConversion / row.storageRatio).toFixed(7)
          );
          console.log("zhuuuuuuu",row.storageUnitquantity)
        }
      }
      //浮动换算就得 填写两个数量计算出浮动率就可以了
      if (row.storageUnitType === 'float') {
        this.handleFloatCalculate(row)
      }
      if(this.activeName =='first'){
        if(row.quantityConversion > row.quantityMax){
          this.$modal.msgWarning("当前转换数量（主）大于库存数量，请修改");
          return
        }
      }

      this.$forceUpdate()
    },
    handleEditFu(index,row) {
      this.$forceUpdate()
      if('Y' == row.enableMultiUnit){
        if (row.storageUnitType === 'fixed') {
          // 主数量=辅 * 换算比例
          row.quantityConversion = parseFloat(
            (row.storageUnitquantity * this.form.storageRatio).toFixed(7)
          );
        }
      }
      //浮动换算就得 填写两个数量计算出浮动率就可以了
      if (row.storageUnitType === 'float') {
        this.handleFloatCalculate(row)
      }
      if(this.activeName == 'first'){
        if(row.quantityConversion > row.quantityMax){
          this.$modal.msgWarning("当前转换数量（主）大于库存数量，请修改");
          return
        }
      }

      this.$forceUpdate()
    },
    handleFloatCalculate(row) {
      //浮动就根据两个数量计算出浮动率就可以了
      if (row.storageUnitquantity > 0 && row.quantityConversion > 0) {
        // 计算新换算比例 = 主数量 / 库存单位数量
        row.storageRatio = parseFloat(
          (row.quantityConversion / row.storageUnitquantity).toFixed(4)
        );
      }
    },
    handleClick(tab, event) {
      console.log(tab.name)
      console.log(tab, event);
    },
    //选择库区
    handleLocationChange(value,row){
      //清空库位
      if(row.areaId){
        this.$set(row, 'areaId', null)
        this.$set(row, 'areaName', null)
        this.$set(row, 'areaCode', null)
      }

      row.locationName=this.locationList.filter(item => item.locationId === value)[0].locationName
      row.locationCode=this.locationList.filter(item => item.locationId === value)[0].locationCode
        // this.getArea(value)

      this.$forceUpdate()
      // this.tableKey++;
    },
    handleVisibleChange(value,row){
      this.areaSelectLoading=true
      if (value) {
        this.getArea(value.locationId)
        this.areaSelectLoading=false
        console.log("qqqqqqqqqq",value)
        // 在这里执行打开下拉框时的操作
      } else {
        console.log('下拉框关闭了');
        // 在这里执行关闭下拉框时的操作
      }

    },
    //选择库位
     handleAreaChange(value,row){
      console.log("11111111111111",row)
          this.$set(row, 'areaName', this.areaList.filter(item => item.areaId === value)[0].areaName)
          this.$set(row, 'areaCode', this.areaList.filter(item => item.areaId === value)[0].areaCode)
      this.$forceUpdate()
    },
    //获取库区
    getLocation(){
      this.locationList=[]
      if(this.form.intWarehouseId){
        getLocationList({warehouseId:this.form.intWarehouseId}).then(response => {
          this.locationList = response.data;
        });
      }

    },
    //获取库位
    getArea(locationId){
      this.areaList=[]
      if(locationId){
        getAreaList({locationId:locationId}).then(response => {
          this.areaList = response.data;
        });
      } else {
        getListByWarehouseId(this.form.intWarehouseId).then(response => {
          this.areaList = response.data;
        });
      }



    },
    /** 新增按钮操作 */
    handleAdd() {
      if('first' == this.activeName){
        if(this.form.outWarehouseId){
          this.$refs.outSelect.showFlag = true;
          this.$refs.outSelect.queryParams.warehouseId = this.form.outWarehouseId;
          this.$refs.outSelect.getList();
        }else{
          this.$modal.msgWarning("请填写出库仓库")
          return
        }

      }
      if('second' == this.activeName){
        if(this.form.intWarehouseId){
          this.$refs.inSelect.showFlag = true;
          this.$refs.inSelect.getList();
        } else {
          this.$modal.msgWarning("请填写入库仓库")
          return
        }

      }
    },

    //装换前选择物料弹出框
    onStockSelected(obj){
      console.log("eeeeeeeeeeeeeee",obj)

      if(obj != undefined && obj != null){

        getMdItem(obj.itemId).then(response => {
          let aa={}
          // this.enableMultiUnit=response.data.enableMultiUnit
          aa.enableMultiUnit=response.data.enableMultiUnit
          aa.storageUnit=response.data.storageUnit
          aa.storageUnitType=response.data.storageUnitType
          aa.storageRatio=response.data.storageRatio

          aa.materialConversionId=this.form.id
          aa.materialConversionType='mcout'
          aa.itemTypeId=obj.itemTypeId
          aa.itemTypeName=obj.itemTypeName
          aa.itemId = obj.itemId;
          aa.itemCode = obj.itemCode;
          aa.itemName = obj.itemName;
          aa.specification = obj.specification;
          aa.unitOfMeasure = obj.unitOfMeasure;
          aa.batchCode = obj.batchCode;
          aa.warehouseId=this.form.outWarehouseId
          aa.warehouseCode=this.form.outWarehouseCode
          aa.warehouseName=this.form.outWarehouseName
          aa.locationId=obj.locationId
          aa.locationCode=obj.locationCode
          aa.locationName=obj.locationName
          aa.areaId=obj.areaId
          aa.areaCode=obj.areaCode
          aa.areaName=obj.areaName
          aa.price=obj.price
          //辅单位
          //库存数量 没保存到数据库  这里获取一下 填数据的时候校验一下
          aa.quantityMax=obj.quantityOnhand

          this.form.beforeList.push(aa)
          this.$forceUpdate()
        })



      }
    },
    // 转换后选择物料弹框
    onItemSelected(obj){
      if(obj != undefined && obj != null){
        obj.autoGenCodeFlag = false
        let aa={}
        aa.materialConversionId=this.form.id
        aa.materialConversionType='mcin'
        aa.itemTypeId=obj.itemTypeId
        aa.itemTypeName=obj.itemTypeName
        aa.itemId = obj.itemId;
        aa.itemCode = obj.itemCode;
        aa.itemName = obj.itemName;
        aa.specification = obj.specification;
        aa.unitOfMeasure = obj.unitOfMeasure;
        aa.batchCode = obj.batchCode;
        aa.warehouseId=this.form.intWarehouseId
        aa.warehouseCode=this.form.intWarehouseCode
        aa.warehouseName=this.form.intWarehouseName

        aa.enableBatchFlag=obj.enableBatchFlag;
//辅单位
        aa.enableMultiUnit=obj.enableMultiUnit
        aa.storageUnit=obj.storageUnit
        aa.storageUnitType=obj.storageUnitType
        aa.storageRatio=obj.storageRatio
        // this.afterForm.afterList.push(obj)
        aa.batchCode=null
        this.form.afterList.push(aa)

        this.$forceUpdate()
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        materialConversionsCode: null,        outWarehouseId: null,        outWarehouseCode: null,        outWarehouseName: null,        intWarehouseId: null,        intWarehouseCode: null,        intWarehouseName: null,        status: null,
        billDate: new Date().toISOString().split('T')[0],        createBy: null,        createByName: null,        createTime: null,        updateBy: null,        updateByName: null,        updateTime: null,        tenantId: null ,enableBatchFlag:null     };
      this.form.beforeList=[]
      this.form.afterList=[]
      this.autoGenFlag=false
      this.resetForm("form");
      this.activeName='first'
   /*   this.form = {
        id: null,        materialConversionId: null,        materialConversionType: null,        itemTypeId: null,        itemTypeName: null,
        itemId: null,        itemCode: null,        itemName: null,        specification: null,        unitOfMeasure: null,
        batchCode: null,        warehouseId: null,        warehouseCode: null,        warehouseName: null,        locationId: null,
        locationCode: null,        locationName: null,        areaId: null,        areaCode: null,        areaName: null,
        quantityConversion: null,        price: null,        recptDate: null,        stockStatus: "0",        manufactureDate: null,
        expireDate: null,        createBy: null,        createByName: null,        createTime: null,        updateBy: null,
        updateByName: null,        updateTime: null,        tenantId: null      };*/
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getLine(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改形态转换单单据体";
      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {

        console.log("sssssssssss",this.form)
        if (valid) {
          for (let i = 0; i < this.form.beforeList.length; i++) {
            if(!this.form.beforeList[i].quantityConversion){
              this.$modal.msgWarning("转换前第"+ (i+1) +"行转换数量不能为空")
              return
            }
          }
          for (let i = 0; i < this.form.afterList.length; i++) {
            console.log("11111111111111",this.form.afterList[i].locationId)
            if(this.form.afterList[i].enableBatchFlag == 'Y'){
              if(!this.form.afterList[i].batchCode){
                this.$modal.msgWarning("转换后第"+ (i+1) +"行批号不能为空")
                return
              }
            }

            if(!this.form.afterList[i].locationId){
              console.log("iiiilocationId",this.form.afterList[i].locationId)
              this.$modal.msgWarning("转换后第"+ (i+1) +"行库区不能为空")
              return
            }
            if(!this.form.afterList[i].areaId){
              console.log("iiiiareaId",this.form.afterList[i].areaId)
              this.$modal.msgWarning("转换后第"+ (i+1) +"行库位不能为空")
              return
            }
            if(!this.form.afterList[i].quantityConversion || this.form.afterList[i].quantityConversion == 0){
              this.$modal.msgWarning("转换后第"+ (i+1) +"行转换数量不能为空")
              return
            }

          }
          if (this.form.id != null) {
            updateMaterialconversionsAll(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.$emit('refreshDataList')

            });
          } else {
            addMaterialconversionsAll(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.$emit('refreshDataList')
            });
          }
        }
      });
    },
   /* submitForm() {
      // 同时验证三个表单
      Promise.all([
        this.$refs.form.validate(),
        this.$refs.beforeForm.validate(),
        this.$refs.afterForm.validate()
      ]).then(() => {
        // 构造提交数据
        const submitData = {
          ...this.form,
          beforeLines: this.beforeForm.beforeList,
          afterLines: this.afterForm.afterList
        }

        if (this.form.id) {
          updateMaterialconversions(submitData).then(response => {
            this.$modal.msgSuccess("修改成功")
            this.open = false
            this.$emit('refreshDataList')
          })
        } else {
          addMaterialconversions(submitData).then(response => {
            this.$modal.msgSuccess("新增成功")
            this.open = false
            this.$emit('refreshDataList')
          })
        }
      }).catch(error => {
        console.log('表单验证失败:', error)
      })
    },*/
    /** 删除按钮操作 */
    handleDelete(index,row) {
 /*     const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除形态转换单单据体编号为"' + ids + '"的数据项？').then(function() {
        return delLine(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});*/
      this.$modal.confirm('是否确认删除该行数据？').then(() => {
        if (this.activeName === 'first') {
          this.form.beforeList.splice(index, 1);
        } else if (this.activeName === 'second') {
          this.form.afterList.splice(index, 1);
        }
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});


    },



    //自动生成批次号
 /*   handleAutoGenCode(autoGenCodeFlag,row) {
      console.log("cccccc",row)
      if (autoGenCodeFlag) {
        genCode('BATCH_CODE_NEW').then(response => {
          row.batchCode = response;

        });
      } else {
        row.batchCode = null;
      }
      this.$forceUpdate()
      this.tableKey++;
    },*/
    async handleLineAutoGenCode(autoGenCodeFlag, row) {
      try {
        if (autoGenCodeFlag) {
          const codedata = await genCode('BATCH_CODE_NEW')
          this.$set(row, 'batchCode', codedata)
        } else {
          this.$set(row, 'batchCode', null)
        }
        // 自动同步开关状态（根据业务需要）
        this.$set(row, 'autoGenCodeFlag', autoGenCodeFlag)
      } catch (error) {
        console.error('生成批次号失败:', error)
        this.$set(row, 'autoGenCodeFlag', !autoGenCodeFlag) // 回滚开关状态
      }
   /*   this.$nextTick(() => {
        this.tableKey++
      })*/
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('wm/line/export', {
        ...this.queryParams
      }, `line_${new Date().getTime()}.xlsx`)
    },
    //自动生成编码
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('MATERIAL_CONVERSIONS_CODE').then(response => {
          this.form.materialConversionsCode = response;
          console.log("aaaaaaaaaaaaaaaaaaaaa",this.form.materialConversionsCode)
          this.$forceUpdate()
        });
      } else {
        this.form.materialConversionsCode = null;
      }
      // this.autoGenFlag=false
      this.$forceUpdate()
    },
    //获取仓库
    getWarehouse(){
      this.warehouseList=[]
      getWarehouseList().then(response => {
        this.warehouseList = response.data.filter((el) =>{
          return el.warehouseCode.indexOf('VIR') == -1;
        })
      });
    },
    //选择出仓库
    handleOutWarehouseChange(value){
      this.form.outWarehouseCode=''
      this.form.outWarehouseName=''
      this.form.outWarehouseName=this.warehouseList.filter(item => item.warehouseId === value)[0].warehouseName
    },
    //选择入仓库
    handleInWarehouseChange(value){
      this.form.intWarehouseCode=''
      this.form.intWarehouseName=''
      this.form.intWarehouseName=this.warehouseList.filter(item => item.warehouseId === value)[0].warehouseName
      this.getLocation()
    },
  }
};
</script>
